﻿#include "journal.h"
#include "ui_journal.h"

Journal::Journal(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::Journal)
{
    ui->setupUi(this);

    table=TD_JOURNAL;
    selectId=0;
    currentMonth=CurrentMonth;

    listModel=new QStringListModel(this);
    ui->listView->setModel(listModel);

    model=new QSqlTableModel(this);
    ui->tableView->setModel(model);

    updateMonth();
    updateDate();
    createMenu();
    updateView();   //手动更新
}

Journal::~Journal()
{
    delete ui;
}

void Journal::keyPressEvent(QKeyEvent *event)
{
    if(event->modifiers() == Qt::ControlModifier && event->key()==Qt::Key_S)
        save();
    else
    {
        switch (event->key()) {
        case Qt::Key_F1:
            newItem();
            break;
        case Qt::Key_F3:
            do_changeStatus();
            break;
        case Qt::Key_F4:
            do_updateDate();
            break;
        case Qt::Key_F5:
            updateView();
            break;
        }
    }
}

void Journal::generateMenu()
{
    menu->addAction(QStringLiteral("新记录... (F1)"),this,&Journal::newItem);
    menu->addSeparator();

    QMenu *m_update=menu->addMenu(QStringLiteral("更新"));
    m_update->addAction(QStringLiteral("更新日期 (F4)"),this,&Journal::do_updateDate);
    m_update->addAction(QStringLiteral("更新视图 (F5)"),this,&Journal::updateView);
    menu->addSeparator();

    menu->addAction(QStringLiteral("编辑备注 (F3)"),this,&Journal::do_changeStatus);
    menu->addAction(QStringLiteral("保存 (Ctrl+S)"),this,&Journal::save);
    menu->addSeparator();

    QMenu *m_option=menu->addMenu(QStringLiteral("选项"));
    m_option->addAction(QStringLiteral("生成记录"),this,&Journal::do_generateSummary);
}

void Journal::do_updateDate()
{
    if(!monthList.contains(CurrentMonth))
        updateMonth();

    if(!dateList.contains(Today))
        updateDate();
}

void Journal::save()
{
    if(model->rowCount() < 1)
        return;

    if(selectId <= 0)
        return;

    QString detail=ui->detail->toPlainText();
    if(detail.isEmpty() || detail == previousDetail)
        return;

    if(sp_updateColumnById(table,"detail",detail,selectId))
        updateView();
    else
        MESSAGE_CANNOT_SAVE
}

void Journal::do_changeStatus()
{
    if(model->rowCount() < 1)
        return;

    if(selectId <= 0)
        return;

    QString status=QInputDialog::getText(this,QStringLiteral("更新备注"),
                                         QStringLiteral("输入："));
    if(status.isEmpty())
        return;

    if(sp_updateColumnById(table,"addition",status,selectId))
        updateView();
    else
        MESSAGE_CANNOT_UPDATE
}

void Journal::newItem()
{
    if(selectDate != Today)
        selectDate = Today;

    J_AddItem item(this);
    if(item.exec() == QDialog::Accepted)
        updateView();

    if(!monthList.contains(currentMonth))
    {
        monthList.append(currentMonth);
        ui->month->addItem(currentMonth);
        ui->month->setCurrentIndex(monthList.size() - 1);
    }
}

void Journal::updateMonth()
{
    if(ui->month->count() != 0)
        ui->month->clear();

    if(!monthList.isEmpty())
        monthList.clear();

    monthList=sp_getCategory("month_",table);
    if(!monthList.isEmpty())
    {
        ui->month->addItems(monthList);
        ui->month->setCurrentIndex(monthList.size() - 1);
    }
}

void Journal::updateDate()
{
    if(selectMonth.isEmpty())
        selectMonth=currentMonth;

    if(listModel->rowCount() != 0)
        listModel->setStringList(QStringList());

    if(!dateList.isEmpty())
        dateList.clear();

    dateList=sp_getCategory("date_",table,"month_",selectMonth);
    if(!dateList.isEmpty())
        listModel->setStringList(sp_reverseList(dateList));
}

void Journal::on_kw_returnPressed()
{
    QString kw=ui->kw->text().trimmed();
    if(kw.isEmpty())
        return;

    model->setTable(table);
    model->setFilter(QString("detail like '%%1%'").arg(kw));
    model->select();

    ui->tableView->hideColumn(ID_COL);   //id
    ui->tableView->hideColumn(MONTH_COL);   //month_
    model->setHeaderData(DATE_COL,Qt::Horizontal,QStringLiteral("日期")); //date_
    model->setHeaderData(CAT_COL,Qt::Horizontal,QStringLiteral("类别")); //category
    model->setHeaderData(DET_COL,Qt::Horizontal,QStringLiteral("事件")); //detail
    ui->tableView->setColumnWidth(DET_COL,DET_WIDTH);
    model->setHeaderData(ADD_COL,Qt::Horizontal,QStringLiteral("备注")); //addition
}

void Journal::on_listView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        selectDate=index.data().toString();
        if(!selectDate.isEmpty())
            updateView();
    }
}

void Journal::updateView()
{
    if(selectDate.isEmpty())
        selectDate=Today;

    model->setTable(table);
    model->setFilter(QString("date_='%1'").arg(selectDate));
    model->select();

    ui->tableView->hideColumn(ID_COL);   //id
    ui->tableView->hideColumn(MONTH_COL);   //month_
    model->setHeaderData(DATE_COL,Qt::Horizontal,QStringLiteral("日期"));;   //date_
    model->setHeaderData(CAT_COL,Qt::Horizontal,QStringLiteral("类别")); //category
    model->setHeaderData(DET_COL,Qt::Horizontal,QStringLiteral("事件")); //detail
    ui->tableView->setColumnWidth(DET_COL,DET_WIDTH);
    model->setHeaderData(ADD_COL,Qt::Horizontal,QStringLiteral("备注")); //addition

    if(model->rowCount() > 0)
        ui->tableView->resizeRowsToContents();

    ui->detail->clear();
}

void Journal::on_tableView_clicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        selectId=sp_fetchId(index);
        previousDetail=sp_fetchString(index,DET_COL);
        ui->detail->setPlainText(previousDetail);
    }
}

// 注意这里的日期！
void Journal::on_tableView_doubleClicked(const QModelIndex &index)
{
    if(previousDetail.isEmpty())
        return;

    QString date=sp_fetchString(index,DATE_COL);
    QString detail=date + " " + previousDetail;
    if(qApp->clipboard()->text() != detail)
        qApp->clipboard()->setText(detail);
}

void Journal::on_month_currentTextChanged(const QString &text)
{
    selectMonth=text;
    updateDate();
}

void Journal::do_generateSummary()
{
    if(selectDate.isEmpty())
        selectDate=Today;

    if(!listModel->stringList().contains(selectDate))
    {
        qApp->clipboard()->setText(QStringLiteral("今日无记录！"));
        return;
    }

    QSqlQuery query;
    query.exec(QString("SELECT category,detail FROM %1 WHERE date_='%2' ORDER BY category")
               .arg(table)
               .arg(selectDate));
    QStringList items;
    while (query.next()) {
        QString category=query.value(0).toString();
        QString detail=query.value(1).toString();
        if(detail.isEmpty())
            continue;

        detail=detail.trimmed();
        if(detail.startsWith("--"))
            continue;

        if(!detail.endsWith(";") && !detail.endsWith(QStringLiteral("；")))
            detail += ";";

        if(category != CAT_JOURNAL)
            items.append(category + QStringLiteral("：") + detail);
        else
            items.append(detail);
    }

    if(!items.isEmpty())
    {
        QString summary=items.join("\n");
        qApp->clipboard()->setText(summary);
    }
    else
        qApp->clipboard()->setText(QStringLiteral("今日无记录！"));
}
